package com.netty.rpc.server;

import com.netty.rpc.config.Config;
import com.netty.rpc.protocol.MessageCodecSharable;
import com.netty.rpc.protocol.ProcotolFrameDecoder;
import com.netty.rpc.server.handler.RpcRequestMessageHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class RpcServer {
    public static void main(String[] args) {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();

        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        RpcRequestMessageHandler RPC_REQUEST_MESSAGE_HANDLER=new RpcRequestMessageHandler();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boss,worker);
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                nioSocketChannel.pipeline().addLast(new ProcotolFrameDecoder());
                nioSocketChannel.pipeline().addLast(LOGGING_HANDLER);
                nioSocketChannel.pipeline().addLast(MESSAGE_CODEC);
                nioSocketChannel.pipeline().addLast(RPC_REQUEST_MESSAGE_HANDLER);
            }
        });
        ChannelFuture conFuture = serverBootstrap.bind(Config.getServerPort());
        conFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                // 成功建立链接
                channelFuture.channel().closeFuture().addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture channelFuture) throws Exception {
                        boss.shutdownGracefully();
                        worker.shutdownGracefully();
                        log.debug("【{}】连接已关闭",this);
                    }
                });
            }
        });
    }
}
